/*
 * Copyright (C) 2011  John Lawrence thegordo.john at gmail.com
 * Licensed under GPLv3 or later. see http://www.gnu.org/copyleft/gpl.html
 */

package org.jklawrencefam.model.email;

/**
 * User: John Lawrence
 * Date: 7/14/11
 * Time: 10:28 PM
 */
public class Address implements Comparable<Address> {
    private String user;
    private String host;
    private AddressType type;
    boolean valid = true;

    public Address(String line) {
        if (line == null) {
            valid = false;
            return;
        }
        String[] parts = line.split(":");
        if (parts.length != 2) {
            valid = false;
            return;
        }
        type = AddressType.discoverAddressType(parts[0]);
        parts = parts[1].trim().split("@");
        if (parts.length != 2) {
            valid = false;
            return;
        }
        if (!(parts[0].startsWith("<") && parts[1].endsWith(">"))) {
            valid = false;
            return;
        }
        user = parts[0].substring(1);
        host = parts[1].substring(0, parts[1].length() - 1);
    }

    public boolean isValid() {
        return valid;
    }

    public String getUser() {
        return user;
    }

    public String getHost() {
        return host;
    }

    public AddressType getType() {
        return type;
    }

    @Override
    public String toString() {
        return "<" + user + "@" + host + ">";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Address address = (Address) o;

        return host.equals(address.host) && type == address.type && user.equals(address.user);

    }

    @Override
    public int hashCode() {
        int result = user.hashCode();
        result = 31 * result + host.hashCode();
        result = 31 * result + type.hashCode();
        return result;
    }

    @Override
    public int compareTo(Address o) {
        return hashCode() - o.hashCode();
    }
}
